import { AxiosRequestConfig } from 'axios';

import { axiosInstance } from './instance';

interface ResponseData<T> {
  code: number
  data: T
  message?: string
}

export const requestUtils = {
  /* 这是封装一个可以适合所有类型请求的方法 */
  request: async <D, Params = any>(url: string, config: AxiosRequestConfig<Params>) => {
    const { data } = await axiosInstance.request<D>({
      ...config,
      url,
    });

    return data;
  },
  get: async <D>(url: string, params?: Record<string, any>) => {
    const { data: res } = await axiosInstance.get<ResponseData<D>>(url, {
      params,
    });

    return res;
  },
  post: async <D>(url: string, data: Record<string, any>) => {
    const { data: res } = await axiosInstance.post<ResponseData<D>>(url, data);

    return res;
  },
  put: async <D>(url: string, data: Record<string, any>) => {
    const { data: res } = await axiosInstance.put<ResponseData<D>>(url, data);

    return res;
  },
  delete: async <D>(url: string, params?: Record<string, any>) => {
    const { data: res } = await axiosInstance.delete<ResponseData<D>>(url, {
      params,
    });

    return res;
  },
};
